﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using XLua;
using System;

public class LuaManager : MonoSingleton<LuaManager> {

	internal static LuaEnv luaEnv = new LuaEnv(); //all lua behaviour shared one luaenv only!
	internal static float lastGCTime = 0;
	internal const float GCInterval = 1;//1 second 

	private LuaTable MainLua;
	private Dictionary<string, LuaTable> tables = new Dictionary<string, LuaTable> ();
	private Dictionary<string, Delegate> delegates = new Dictionary<string, Delegate>();

	void Update() {
		if (Time.time - LuaBehaviour.lastGCTime > GCInterval)
		{
			luaEnv.Tick();
			LuaBehaviour.lastGCTime = Time.time;
		}
	}

	public void CallFunction(string tableName, string funcName) {
		string fullName = tableName + "." + funcName;
		if (delegates.ContainsKey (fullName)) {
			Action act = delegates [fullName] as Action;
			if (act != null) {
				act ();
				return;
			}
		}
		if (!tables.ContainsKey (tableName)) {
			LuaTable table = MainLua.Get<LuaTable> (tableName);
			if (table != null) {
				tables [tableName] = table;
			}
		}
		if (tables.ContainsKey (tableName)) {
			Action act = tables [tableName].Get<Action> (funcName);
			if (act != null) {
				delegates [fullName] = act;
				act ();
			}
		}
	}

	public void Main() {

		luaEnv.AddLoader((ref string filename) => {
			BinaryObject loader = ResourceManager.Instance.GetResource ("lua/" + filename + ".lua.txt", typeof(TextAsset), enResourceType.Lua).m_content as BinaryObject;
			return loader.m_data;
		});
			
		MainLua = LuaManager.luaEnv.NewTable();
		LuaTable meta = LuaManager.luaEnv.NewTable();
		meta.Set("__index", LuaManager.luaEnv.Global);
		MainLua.SetMetaTable(meta);
		meta.Dispose();

		BinaryObject bo = ResourceManager.Instance.GetResource ("lua/Main.lua.txt", typeof(TextAsset), enResourceType.Lua).m_content as BinaryObject;
		if (bo != null) {
			LuaManager.luaEnv.DoString(bo.m_data, gameObject.name, MainLua);
			Action main = MainLua.Get<Action>("Main");
			main ();

			tables["FormManager"] = MainLua.Get<LuaTable> ("FormManager");
			tables["Hotfix"] = MainLua.Get<LuaTable> ("Hotfix");
		}
	}
}
